package org.swift.mashup.engine.deployment.mcr;

import org.apache.axis2.context.MessageContext;
import org.apache.axis2.transport.http.HTTPConstants;
import org.swift.mashup.engine.deployment.MessageContextReader;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

public class URLMessageContextReader implements MessageContextReader {

	public static final String BASE_URL = "baseUrl";
	public static final String SERVICE_URL = "serviceUrl";
	private static final String SERVICES_CONTEXT = "/services";

	private static URLMessageContextReader instance = null;

	public static URLMessageContextReader getInstance() {
		if (instance == null) {
			instance = new URLMessageContextReader();
		}
		return instance;
	}

	private URLMessageContextReader() {
	}

	@Override
	public Map<String, Object> createParameterMap(MessageContext context) {
		Map<String,Object> paramMap = new HashMap<String,Object>();

		HttpServletRequest req = (HttpServletRequest)context.getProperty(HTTPConstants.MC_HTTP_SERVLETREQUEST);
		String serviceUrl = req.getRequestURL().toString();
		String baseUrl = serviceUrl.substring(0, serviceUrl.lastIndexOf(SERVICES_CONTEXT)+SERVICES_CONTEXT.length());

		paramMap.put(BASE_URL, baseUrl);
		paramMap.put(SERVICE_URL, serviceUrl);

		return paramMap;
	}
}
